package com.ys.controller.api.finance;

import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSON;
import com.ys.entity.business.TpAmazonShop;
import com.ys.entity.finance.TcwStoreAccount;
import com.ys.enume.AmazonSellerEnum;
import com.ys.mapper.business.DiySqlMapper;
import com.ys.service.finance.TcwFinancesApiDataService;
import com.ys.service.log.ApiLogService;
import com.ys.util.admin.ConditionUtil;
import com.ys.util.dhecp.DateUtils;
import com.ys.vo.ApiResponse;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ys.entity.finance.TcwFinancesEventGroups;
import com.ys.entity.sys.YsCol;
import com.ys.enume.sys.YsColEnum;
import com.ys.service.sys.CommonApiService;
import com.ys.service.sys.UploadService;
import com.ys.util.ExportExcelUtils;
import com.ys.vo.LayuiTableVoJA;
import com.ys.vo.R;

@Controller
@RequestMapping("/api/inter/tcwFinancesEventGroups")
public class ApiInterTcwFinancesEventGroupsController {

	public static Long MENU_ID = 81L;
	private static org.slf4j.Logger logger = LoggerFactory.getLogger(ApiInterTcwFinancesEventGroupsController.class);

	private Object lock = new Object();


	@Autowired
	private CommonApiService<TcwFinancesEventGroups> commonApiService;

	@Autowired
	private TcwFinancesApiDataService tcwFinancesApiDataService;

	@Autowired
	private DiySqlMapper diySqlMapper;

	@Autowired
	private ApiLogService apiLogService;

	@RequiresPermissions("tcwFinancesEventGroups:view")
	@RequestMapping("/search")
    @ResponseBody
	public LayuiTableVoJA search(@ModelAttribute TcwFinancesEventGroups cond,String conditions){
		String eventDetailStatus = ConditionUtil.getConditionValue(conditions, "eventDetailStatus");
		cond.addField("(CASE WHEN A.currencyAmount = A.TwoCurrencyAmount THEN 'YES' ELSE 'NO' END) as eventDetailStatus");
		cond.setOrderby("A.ShopName asc");
		return commonApiService.searchLay(cond);
	}

	@RequestMapping("/export")
	@ResponseBody
	public R export(@ModelAttribute TcwFinancesEventGroups cond, String conditions) throws Exception{

		cond.setPage(0).setSize(999999);

		List<Map<String, Object>> listData = cond
				.addField("(CASE WHEN A.currencyAmount = A.TwoCurrencyAmount THEN 'YES' ELSE 'NO' END) as eventDetailStatus")
				.queryMap();

		List<YsCol> listField = new YsCol()
				.setMenuId(MENU_ID)
				.setFrontShow(YsColEnum.FrontShow.SHOW.value)
				.setOrderby("A.SortNo asc")
				.queryList();


		ExportExcelUtils<TcwFinancesEventGroups> util = new ExportExcelUtils<TcwFinancesEventGroups>(new TcwFinancesEventGroups());

		String toFilePath = util.exportExcel(listData, listField, "财务事件表");
		UploadService.UploadDto dto = commonApiService.uploadLocalToServer(toFilePath);
		return R.ok(dto.getUrl());
	}



	/**
	 * 新增
	 * @throws Exception
	 */
	@RequiresPermissions("tcwPointTransfer:add")
	@PostMapping("/refresh")
	@ResponseBody
	public R refresh(String shopNameMc, String financesEventGroupsYf,String year,String companyID) throws Exception{
		synchronized (lock) {
			// 临界区代码
			Calendar cal = Calendar.getInstance();
			int dayOfWeek = cal.get(Calendar.DAY_OF_WEEK); // 获取当前是星期几
			int weekOfMonth = cal.get(Calendar.WEEK_OF_MONTH); // 获取当前是月份的第几周

			if (dayOfWeek == Calendar.SUNDAY && weekOfMonth == 1) {
				return R.error("今天是每月第一周的星期天不允许重新刷新");
			}
			int yearint = Integer.parseInt(year);
			int month = Integer.parseInt(financesEventGroupsYf);
			//月份第一天
			Calendar calendar = Calendar.getInstance();
			calendar.set(yearint,month-1,1);
			calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMinimum(Calendar.DAY_OF_MONTH));
			//月份最后一天
			Calendar calendar1 = Calendar.getInstance();
			calendar1.set(yearint,month-1,20);
			calendar1.set(Calendar.DAY_OF_MONTH, calendar1.getActualMaximum(Calendar.DAY_OF_MONTH));

			calendar.set(Calendar.HOUR_OF_DAY,00);
			calendar.set(Calendar.MINUTE,00);
			calendar.set(Calendar.SECOND,00);

			calendar1.set(Calendar.HOUR_OF_DAY,23);
			calendar1.set(Calendar.MINUTE,59);
			calendar1.set(Calendar.SECOND,59);

			Date startTime = calendar.getTime();
			String startTimeStr = DateUtils.convertDateToTDate(startTime);
			Date endTime = calendar1.getTime();
			String endTimeStr = DateUtils.convertDateToTDate(endTime);

			TcwStoreAccount tcwStoreAccount = null;
			//删除表中数据
			diySqlMapper.deleteFinancesApiData();
			//查询所有店铺信息
			List<TpAmazonShop> tpAmazonShopList = new TpAmazonShop()
					.where("A.authorizeState = '已授权' AND A.companyID = '" + companyID + "'")
					.setOrderby("A.Id asc")
					.queryList();
			for (TpAmazonShop tpAmazonShop : tpAmazonShopList) {
				//大站点授权一样,所以取其中两个小站点
//				if (tpAmazonShop.getCountryName().equals(AmazonSellerEnum.GB.getCnName()) || tpAmazonShop.getCountryName().equals(AmazonSellerEnum.US.getCnName())) {
//					ApiResponse apiResponse = tcwFinancesApiDataService.getFinancesApi(tpAmazonShop, startTimeStr, endTimeStr, tpAmazonShopList, tcwStoreAccount);
					ApiResponse apiResponse = null;
					if (apiResponse.getCode() == 500) {
						apiLogService.addApiLog("Amazon", "GetFinancesApiWeb", "ECP_API定时获取亚马逊财务事件信息出错，条件queryParams：" + JSON.toJSONString(tpAmazonShop), "店铺:" + tpAmazonShop.getShopName(), apiResponse.getCode(), apiResponse.getMessage());
						return R.error("刷新失败,"+ apiResponse.getMessage());

					}
					logger.info("***********每月定时新增财务目录GetFinancesApiWeb，结束***********");

					logger.info("***********每月定时新增财务事件明细GetFinancesInfoWeb，开始***********");
//					apiResponse = tcwFinancesApiDataService.getFinancesInfo(tpAmazonShop, startTimeStr, endTimeStr, tcwStoreAccount);
					apiResponse = null;
					if (apiResponse.getCode() == 500) {
						apiLogService.addApiLog("Amazon", "GetFinancesInfoWeb", "ECP_API定时获取亚马逊财务事件信息出错，条件queryParams：" + JSON.toJSONString(tpAmazonShop), "店铺:" + tpAmazonShop.getShopName(), apiResponse.getCode(), apiResponse.getMessage());
						return R.error("刷新失败,"+ apiResponse.getMessage());
					}
					logger.info("***********每月定时新增财务事件明细GetFinancesInfoWeb，结束***********");
//				}
			}
		}
		return R.ok("刷新成功");
	}

//	@RequestMapping("/search11")
//	@ResponseBody
//	public R search11(String shopNameMc, String financesEventGroupsYf,String year,String companyID) throws Exception{
//		synchronized (lock) {
//			// 临界区代码
//			Calendar cal = Calendar.getInstance();
//			int dayOfWeek = cal.get(Calendar.DAY_OF_WEEK); // 获取当前是星期几
//			int weekOfMonth = cal.get(Calendar.WEEK_OF_MONTH); // 获取当前是月份的第几周
//
//			if (dayOfWeek == Calendar.SUNDAY && weekOfMonth == 1) {
//				return R.error("今天是每月第一周的星期天不允许重新刷新");
//			}
//			int yearint = Integer.parseInt(year);
//			int month = Integer.parseInt(financesEventGroupsYf);
//			//月份第一天
//			Calendar calendar = Calendar.getInstance();
//			calendar.set(yearint,month-1,1);
//			calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMinimum(Calendar.DAY_OF_MONTH));
//			//月份最后一天
//			Calendar calendar1 = Calendar.getInstance();
//			calendar1.set(yearint,month-1,20);
//			calendar1.set(Calendar.DAY_OF_MONTH, calendar1.getActualMaximum(Calendar.DAY_OF_MONTH));
//
//			calendar.set(Calendar.HOUR_OF_DAY,00);
//			calendar.set(Calendar.MINUTE,00);
//			calendar.set(Calendar.SECOND,00);
//
//			calendar1.set(Calendar.HOUR_OF_DAY,23);
//			calendar1.set(Calendar.MINUTE,59);
//			calendar1.set(Calendar.SECOND,59);
//
//			Date startTime = calendar.getTime();
//			String startTimeStr = DateUtils.convertDateToTDate(startTime);
//			Date endTime = calendar1.getTime();
//			String endTimeStr = DateUtils.convertDateToTDate(endTime);
//
//			TcwStoreAccount tcwStoreAccount = null;
//			//删除表中数据
//			diySqlMapper.deleteFinancesApiData();
//			//查询所有店铺信息
//			List<TpAmazonShop> tpAmazonShopList = new TpAmazonShop()
//					.where("A.authorizeState = '已授权' AND A.companyID = '" + companyID + "'")
//					.setOrderby("A.Id asc")
//					.queryList();
//			for (TpAmazonShop tpAmazonShop : tpAmazonShopList) {
//				//大站点授权一样,所以取其中两个小站点
//				if (tpAmazonShop.getCountryName().equals(AmazonSellerEnum.GB.getCnName()) || tpAmazonShop.getCountryName().equals(AmazonSellerEnum.US.getCnName())) {
//					ApiResponse apiResponse = tcwFinancesApiDataService.getFinancesApi(tpAmazonShop, startTimeStr, endTimeStr, tpAmazonShopList, tcwStoreAccount);
//					if (apiResponse.getCode() == 500) {
//						apiLogService.addApiLog("Amazon", "GetFinancesApiWeb", "ECP_API定时获取亚马逊财务事件信息出错，条件queryParams：" + JSON.toJSONString(tpAmazonShop), "店铺:" + tpAmazonShop.getShopName(), apiResponse.getCode(), apiResponse.getMessage());
//						return R.error("刷新失败,"+ apiResponse.getMessage());
//
//					}
//					logger.info("***********每月定时新增财务目录GetFinancesApiWeb，结束***********");
//
//					logger.info("***********每月定时新增财务事件明细GetFinancesInfoWeb，开始***********");
//					apiResponse = tcwFinancesApiDataService.getFinancesInfo(tpAmazonShop, startTimeStr, endTimeStr, tcwStoreAccount);
//					if (apiResponse.getCode() == 500) {
//						apiLogService.addApiLog("Amazon", "GetFinancesInfoWeb", "ECP_API定时获取亚马逊财务事件信息出错，条件queryParams：" + JSON.toJSONString(tpAmazonShop), "店铺:" + tpAmazonShop.getShopName(), apiResponse.getCode(), apiResponse.getMessage());
//						return R.error("刷新失败,"+ apiResponse.getMessage());
//					}
//					logger.info("***********每月定时新增财务事件明细GetFinancesInfoWeb，结束***********");
//				}
//			}
//		}
//		return R.ok("刷新成功");
//	}
}
